﻿using Microsoft.AspNetCore.Authorization;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Sykj.Components
{
    /// <summary>
    /// 权限授权Handler
    /// </summary>
    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            //从AuthorizationHandlerContext转成HttpContext，以便取出表求信息
            var httpContext = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).HttpContext;
            var routeData = (context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext).RouteData.Values;
            var controller = routeData["controller"];
            var action = routeData["action"];

            //请求的控制器与action
            var url = string.Format("/{0}/{1}/{2}", Constant.AREAMANAGER, controller, action).ToLower();
            //是否经过验证
            var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
            if (isAuthenticated)
            {
                int userId = int.Parse(context.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Sid).Value);
                List<Sykj.Entity.Roles> rolesList = new List<Entity.Roles>();
                string r = context.User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Role).Value;
                if (!string.IsNullOrWhiteSpace(r))
                {
                    rolesList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Sykj.Entity.Roles>>(r);
                }
                var PermissionsList = requirement.User.GetPermissionsList(userId, rolesList);
                int c = PermissionsList.Where(w => w.Url == url && w.Type > 1).Count();
                if (c>0)
                {
                    context.Succeed(requirement);
                }
            }
            return Task.CompletedTask;
        }
    }
}
